//
//  APIClient.swift
//  shop
//
//  Created by 刘伟 on 2017/3/10.
//
//

import Alamofire

// MARK: 接口请求返回类型
enum ClientResponseType {
    case success(AnyObject, String)
    case failure(String)
    case relogin(String)
}

let APIURL = "http://api.liteaccount.cn/?service="

class APIClient {
    // 单例
    private static let singleInstance = APIClient()
    
    class var shared: APIClient {
        return singleInstance
    }
    
    // MARK: 默认请求，将 Alamofire 返回的结果按照约定处理成需要的形式
    func defaultRequest(url: String, params: [String: Any]?,method: HTTPMethod = .post, showMessage: Bool = false, getResult: @escaping (_ result: ClientResponseType) -> Void) {
        Alamofire.request(url, method: method, parameters: params).responseJSON(completionHandler: { (response) in
            let result: ClientResponseType!
            // 简化流程：如果获取不多数据就说明网络异常
            guard let data = response.result.value else {
                result = ClientResponseType.failure("网络异常")
                getResult(result)
                ProgressHUD.showError("网络异常")
                return
            }
            let json = JSON(data)
            guard let ret = json["ret"].int, let msg = json["msg"].string else {
                result = ClientResponseType.failure("网络异常")
                getResult(result)
                ProgressHUD.showError("网络异常")
                return
            }
            
            if ret != 200 {
                result = ClientResponseType.failure(msg)
                getResult(result)
                ProgressHUD.showError(msg)
                return
            }
            
            guard let status = json["data"]["code"].int, let message = json["data"]["msg"].string else {
                result = ClientResponseType.failure("网络异常")
                getResult(result)
                ProgressHUD.showError("网络异常")
                return
            }
            switch status {
            case 0:
                result = ClientResponseType.success(json["data"]["info"] as AnyObject, message)
            case -1:
                result = ClientResponseType.failure(message)
            case -2:
                resetDefaults()
                result = ClientResponseType.relogin(message)
            default:
                result = ClientResponseType.failure("数据异常")
            }
            getResult(result)
            self.showRequestMessage(result, showSuccess: showMessage)
        })
    }
    
    func showRequestMessage(_ result: ClientResponseType, showSuccess: Bool) {
        switch result {
        case let .success(_, message):
            if showSuccess {
                ProgressHUD.showSuccess(message)
            }
        case let .failure(message):
            ProgressHUD.showError(message)
        case let .relogin(message):
            ProgressHUD.showError(message)
        }
    }
    
}
